﻿using System;
using System.Collections;
using System.Text;

/// <summary>
/// 数据流组包器
/// </summary>
public class EPacket
{
    protected ArrayList m_Buffer;   // 后备的数据缓冲区
    protected int m_iWPos;          // 当前写指针的位置

    // 构造函数
    public EPacket()
    {
        m_Buffer = new ArrayList(2048);
    }

    // 构造函数
    public EPacket(int initSize)
    {
        m_Buffer = new ArrayList(initSize);
    }

    // 得到内部缓冲区首地址
    public byte[] GetPacketBuffer()
    {
        return (byte[])m_Buffer.ToArray(typeof(byte));
    }

    // 得到数据区内所有有效数据的长度
    public int Size()
    {
        return m_iWPos;
    }

    // 得到当前写指针的位置
    public int GetWritePos()
    {
        return m_iWPos;
    }

    // 设置写指针的位置
    public void SetWritePos(int pos)
    {
        m_iWPos = pos;
    }

    // 清空数据
    public void Clear()
    {
        m_Buffer = null;
        m_iWPos = 0;
    }

    // 压入Byte数据
    public void WriteByte(byte param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(byte));
    }

    // 压入Char数据
    public void WriteChar(char param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(char));
    }

    // 压入布尔数据
    public void WriteBoolean(bool param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(bool));
    }

    // 压入整形数据
    public void WriteInt(short param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(short));
    }

    // 压入整形数据
    public void WriteInt(int param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(int));
    }

    // 压入浮点数据
    public void WriteFloat(float param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(float));
    }

    // 压入Long数据
    public void WriteLong(long param)
    {
        byte[] buffer = BitConverter.GetBytes(param);
        Write(buffer, sizeof(long));
    }

    // 压入字符串数据(UTF8格式存储)
    public void WriteString(string param)
    {
        if (param.Length <= 0)
        {
            WriteInt(0); return;
        }

        byte[] array = Encoding.UTF8.GetBytes(param);
        // 对于字符串，则先存储对应长度
        WriteInt(array.Length);

        // 挨个存储字节
        for (int i = 0; i < array.Length; i++)
        {
            m_Buffer.Add(array[i]);
            m_iWPos += 1;
        }
    }

    // 压入字符串数据
    public void WriteString(byte[] buffer, int len)
    {
        for (int i = 0; i < len; i++)
        {
            m_Buffer.Add(buffer[i]);
            m_iWPos += 1;
        }
    }

    // 添加一定长度的数据
    public void Write(byte[] buffer, int length)
    {
        for (int i = 0; i < length; i++)
        {
            m_Buffer.Add(buffer[i]);
            m_iWPos += 1;
        }
    }
}